package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.property.service.IPropertyAddEquipService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * <desc>
 *      添加或更新或删除sip消费者
 * </desc>
 *
 * @createDate 2017/10/30
 */
@Component
public class SyncEquipSipWhenEnableCloudConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(SyncEquipSipWhenEnableCloudConsumer.class);

    //物业sip服务层
    @Autowired
    IPropertyAddEquipService iPropertyAddEquipService;


    /**
     * <desc>
     *      运营启用云对讲时，同步项目中云对讲设备的Sip
     * <desc/>
     * @param   message 消息数据
     * @author Biao.R
     * @createDate 2017/10/30
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_SYNC_EQUIP_SIP_WHEN_ENABLE_CLOUD_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        //LOG.info("【RabbitMQ_运营启用云对讲时，同步项目中云对讲设备的Sip消费者】:处理异常:" + body);
        try {

            TimeTaskDeadMessageQueuePO deadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            JSONObject datajs = JSON.parseObject(deadMessageQueuePO.getMessageContent());

            String projectId = datajs.getString("data");
            if (StringUtils.isNotEmpty(projectId)) {
                //LOG.info("===RabbitMQ_运营启用云对讲时，同步项目中云对讲设备的Sip消费者:" + projectId);
                iPropertyAddEquipService.syncEquipSipWhenEnableCloud(projectId);
            }
        } catch (Exception e) {
            LOG.error("【RabbitMQ_运营启用云对讲时，同步项目中云对讲设备的Sip消费者】:处理异常:", e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}